import axios from 'axios'
import type { CustomConfig, PostParam } from '@/api/http-client-param'
import { DEFAULT_CUSTOM_CONFIG } from '@/api/http-client-param'
import { error } from '@/components/messages/message-service'

function makeInstance() {
  const instance = axios.create()
  instance.interceptors.response.use(
    (res) => {
      if (res.data && res.data.status === 1) {
        return res.data.data
      } else {
        const customConfig = (res.config as any).customConfig as CustomConfig
        if (customConfig && customConfig.showErrorMessage) {
          error(`${res.data.msg}:${res.data.detail}`)
        }
        throw res.data
      }
    },
    (res) => {
      console.error(res)
      error(`${res.code}: ${res.response?.status}-${res.response?.statusText}: ${res.config?.url}`)
      throw res
    }
  )
  return instance
}

const prefix = '/api'

const defaultInstance = makeInstance()

function mergeConfig(config?: CustomConfig) {
  if (!config) {
    return Object.assign({}, DEFAULT_CUSTOM_CONFIG)
  }
  return Object.assign({}, DEFAULT_CUSTOM_CONFIG, config)
}

export function post(param: PostParam) {
  const config: { [key: string]: any } = {}
  config.customConfig = mergeConfig(param.customConfig)
  return defaultInstance.post(`${prefix}${param.url}`, param.data, config)
}
